const inquirer = require('inquirer') // 导入问答库
const download = require('download-git-repo') // 导入远程仓库下载库
const ora = require('ora') // 导入 loading 加载库
const chalk = require('chalk') // 导入终端字体样式修改库

const { projectTypeList, projectUrlList } = require('../../config')

module.exports = async () => {
  const questions = [
    {
      type: 'input',
      name: 'projectName',
      message: '请输入项目名',
      default: 'my-project'
    },
    {
      type: 'list',
      name: 'projectType',
      message: '请选择项目类型',
      // choices: ['node', 'express', 'koa', 'egg']
      choices: projectTypeList
    }
  ]
  try {
    // 自定义问答
    const answers = await inquirer.prompt(questions)
    const { projectName, projectType } = answers

    // 根据项目类型去远端下载模版
    let repoUrl = `direct:${projectUrlList[projectType]}`
    // 添加终端旋转 Loading 效果
    const spinner = ora('Loading...').start()
    // 下载 git 远程仓库代码
    download(repoUrl, projectName + '/', { clone: true }, err => {
      if(!err) {
        spinner.succeed(chalk.green('Succeed'))
        console.log(chalk.blue.bold('Done!'), chalk.bold('you can run:'));
        console.log('cd ' + projectName);
        console.log('npm install ');
        console.log('npm run dev ');
        return
      }
      spinner.fail(chalk.red(err))
    })
  }catch (e) {
    throw new Error(e)
  }
}
